/**
 * 
 */
package zhoujian.oj.leetcode;

import org.junit.Test;

/**
 * @author hyper
 * @email zjkermit@gmail.com
 * @date Dec 19, 2013
 * @version 1.0
 * @description 
 * 	Reverse digits of an integer.
 * 		Example1: x = 123, return 321
 * 		Example2: x = -123, return -321
 */
public class ReverseInteger {

	public int reverse(int x) {
		if (Math.abs(x) < 10) {
			return x;
		}
		
		boolean sign = true;
		if (x < 0) {
			sign = false;
		}
		
		char[] ch = String.valueOf(Math.abs(x)).toCharArray();
		// reverse
		int n = ch.length;
		for (int i = 0; i < n / 2; i++) {
			char t = ch[i];
			ch[i] = ch[n - 1 - i];
			ch[n - 1 - i] = t;
		}
		
		return sign ? Integer.valueOf(String.valueOf(ch)) : -Integer.valueOf(String.valueOf(ch));
	}
	
	@Test
	public void testReverse() {
		assert reverse(901000) == 109;
		assert reverse(123) == 321;
		assert reverse(-123) == -321;
	}
}
